package com.cn.scenario.shiroconfig.util.JWT;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtil {

    public static String createBearerToken(String userName){
        return "Bearer " + createToken(userName);
    }

    /**
     * 创建token
     * @param userName 用户名
     * @return 创建的token
     */
    public static String createToken(String userName){
        // token的过期时间
        long current = System.currentTimeMillis() / 1000;
        Date date = new Date((current + JWTConfig.expiration)*1000);
        // jwt的header部分
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // 创建token
        String token;
        try {
            token = JWT.create()
                    .withHeader(map) //header部分
                    .withClaim(JWTConfig.authoritiesKey, userName) //存储用户信息
                    .withClaim("current", current) //当前的时间戳
                    .withExpiresAt(date) //过期时间
                    .withIssuedAt(new Date(current)) //签发时间
                    .sign(Algorithm.HMAC256(JWTConfig.secret)); //私钥
        } catch (Exception e){
            log.error("为用户{}创建token失败", userName);
            throw new RuntimeException("为用户创建token失败", e);
        }
        return token;
    }

    /**
     * 校验token
     * @param token 传入的token
     * @return 是否校验通过
     */
    public static boolean verifyToken(String token) throws AuthenticationException {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JWTConfig.secret)).build();
            verifier.verify(token);
            return true;
        } catch (Exception e){
            log.error("校验token={}失败", token, e);
            throw e;
        }
    }

    /**
     * 从token中获取用户信息
     * @param token 传入的token
     * @return 用户信息
     */
    public static String getUserInfo(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(JWTConfig.authoritiesKey).asString();
        } catch (Exception e){
            log.error("从token={}中获取用户信息失败", token, e);
            return null;
        }
    }

    /**
     * 判断是否过期
     */
    public static boolean isExpire(String token) {
        DecodedJWT jwt = JWT.decode(token);
        System.out.println(jwt.getExpiresAt().getTime());
        System.out.println(System.currentTimeMillis());
        return jwt.getExpiresAt().getTime() < System.currentTimeMillis();
    }

    public static void main(String[] args){
        String token = JWTUtil.createToken("admin");
        System.out.println(token);

        boolean result = JWTUtil.verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXJyZW50IjoxNjc5MzA2NjcxOTczLCJ1c2VyTmFtZSI6ImFkbWluIiwiZXhwIjoxNjc5MzEwMjcxLCJpYXQiOjE2NzkzMDY2NzF9.KGrVR6Or28T1BKdrI5qaOtnrd3JxzGOt_2Ru1TXtaHI");
        System.out.println(result);
    }
}
